<template>
	<div class="page">
		<div class="welcome">
			<div class="w u-m-b-10">欢迎使用</div>
			<div class="big">微聊</div>
		</div>
		<!-- 分区选择器 -->
		<view class="zone-picker u-m-b-40">
			<picker :range="zoneDisplayList" @change="onZoneChange">
				<view class="online-count">
					<text>{{ selectedZoneDisplay || '请选择分区' }}</text>
					<u-icon name="arrow-down" size="18" color="#666" style="margin-left: 10rpx;" />
				</view>
			</picker>
		</view>

		<div class="login-wrap">
			<div class="login-type u-m-b-50" v-if="type == 'login'">
				<!-- <div @tap="loginType = 'codeLogin'" :class="{ text_line: loginType == 'codeLogin' }" class="u-m-r-60">验证码登录</div> -->
				<div @tap="loginType = 'passwordLogin'" :class="{ text_line: loginType == 'passwordLogin' }">密码登录</div>
			</div>

			<div class="input-wrap">
				<u-input v-model="form.username" class="u-m-b-60" type="number" :custom-style="customStyle"
					placeholder="请输入手机号" />

				<div class="u-flex flex-between u-m-b-60" v-if="loginType == 'codeLogin'">
					<u-input v-model="code" placeholder="请输入验证码" type="number" :custom-style="customStyle" />
					<div v-if="show" @click="getVerificationCode" class="getCode">
						获取验证码
					</div>
					<div v-else class="getCode">{{ count }}s</div>
				</div>

				<u-input v-model="form.password" v-if="loginType == 'passwordLogin'" type="password"
					:custom-style="customStyle" placeholder="请输入密码" />

				<u-input v-model="register_password" v-if="type == 'registered'" type="password"
					:custom-style="customStyle" placeholder="请设置密码（含大小写、数字）" />
			</div>

			<div class="submit">
				<div class="l" v-if="type == 'login'">
					<div @tap="submit" class="btn">登录</div>
					<div class="u-flex flex-between u-m-t-30">
						<view @click="goRegister" class="login-footer-box-left">注册新用户</view>
					</div>
				</div>

				<!-- <div class="r" v-if="type == 'registered'">
					<div @tap="register()" class="btn">
						注册
					</div>
					<div class="u-m-t-30 u-flex flex-center" @tap="type = 'login';loginType='passwordLogin'">已有帐号登录
					</div>
				</div> -->
			</div>
		</div>

		<div v-if="type == 'registered'" @tap="toPage('/pages/center/register', { type: 1 })" class="reading">
			注册表示同意 <text style="color: black;">《使用协议》</text>
		</div>
		<div v-else @tap="toPage('/pages/agreement/index', { type: 1 })" class="reading">
			登录微聊即表示同意 <text style="color: black;">《使用协议》</text>
		</div>
	</div>
</template>

<script>
	import Config from "@/common/config.js"; // 本地配置数据
	import appDialog from '../../node_modules/js_sdk/dialog';
	import {
		genTestUserSig
	} from '../../debug/GenerateTestUserSig.js';
	export default {
		data() {
			return {
				zoneList: [],
				zoneDisplayList: [],
				selectedZoneDisplay: '',
				isShowSliderVerify: false,
				type: "login",
				phone: "",
				password: "",
				code: "",
				register_password: "",
				loginType: "passwordLogin",
				customStyle: {
					borderBottom: "1rpx solid #A0A0A0",
					paddingLeft: "10rpx",
				},
				btnMsg: "获取验证码",
				count: "",
				timer: null,
				show: true,
				tabIndex: 0,
				form: {
					mobile: '',
					username: '',
					password: '',
					captcha: '',
					domain: '' // 用于记录选中的 domain 值
				},
				rules: {
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['blur'],
						}
					],
					username: [{
						required: true,
						message: '请输入账号',
						trigger: ['change', 'blur']
					}],
					password: [{
						required: true,
						min: 6,
						message: '请输入正确的密码',
						trigger: 'blur'
					}],
					// captcha: [{
					// 	required: true,
					// 	min: 4,
					// 	message: '请输入正确的验证码',
					// 	trigger: ['change', 'blur']
					// }]
				},
				loginFormButtonStyle: {
					backgroundImage: "linear-gradient(to bottom right, #34E4E8, #1FAEE8)",
					border: 'none',
					color: '#ffffff',
					outline: 'none',
					marginTop: '80rpx',
					height: '100rpx',
					width: '100rpx'
				},
				// loginFormButtonDisabled: false,
				// modelShow: false,
				// modelContent: '',
				// codeTips: '请输入验证码',
				// commonTips: '',
				// captchaPath: ''
			}
		},
		onLoad() {
			this.getZoneDomains();
			// #ifndef H5
			this.checkForUpdate() // 检查版本更新
			// #endif
		},
		onReady() {
			this.downloadCaptcha()
			// this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			checkForUpdate() {
				const that = this;
				console.log("检查版本更新")
				// 获取当前版本号是异步的
				that.getCurrentVersionCode().then(currentVersionCode => {
					console.log("当前版本号:", currentVersionCode);
			
					this.$u.get(`/api/Redpacket/getLatestAppVersion`)
						.then(res => {
							if (res.status === 'success' && res.data) {
								const latestVersion = res.data;
								console.log("检查版本更新s")
								console.log(res)
								console.log(latestVersion)
								// 假设 version 是字符串如 "2.0.0"，可以用某种方式转成整数版本号，也可以让后端返回 version_code
								const latestVersionCode = parseInt(latestVersion.version.replace(/\D/g, '')) ||
									0;
								console.log("服务端返回版本号:", latestVersionCode);
			
								if (latestVersionCode > currentVersionCode) {
									// 根据 force_update 字段决定是否允许取消按钮
									const isForceUpdate = latestVersion.force_update === 1;
									appDialog.show(latestVersion.download_url, latestVersion.update_message, isForceUpdate);
								} else {
									// uni.showToast({
									// 	title: '当前已是最新版',
									// 	icon: 'none'
									// });
								}
							} else {
								// uni.showToast({
								// 	title: '版本检查失败',
								// 	icon: 'none'
								// });
							}
						})
						.catch(err => {
							console.error('版本检查请求失败：', err);
							// uni.showToast({
							// 	title: '请求失败，请稍后重试',
							// 	icon: 'none'
							// });
						});
				});
			},
			
			getCurrentVersionCode() {
				return new Promise((resolve) => {
					plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
						resolve(parseInt(wgtinfo.versionCode));
					});
				});
			},
			// 获取分区信息
			getZoneDomains() {
				this.$u.get(`/api/Redpacket/getZoneDomains`)
					.then(res => {
						if (res.status === 'success') {
							this.zoneList = res.data;
							this.zoneDisplayList = res.data.map(item =>
								`${item.name}（在线：${item.online_count}/人）`
							);
							
							// 查找在线人数最少的分区索引
							if (this.zoneList.length > 0) {
								let minIndex = 0;
								let minCount = this.zoneList[0].online_count;
								for (let i = 1; i < this.zoneList.length; i++) {
									if (this.zoneList[i].online_count < minCount) {
										minCount = this.zoneList[i].online_count;
										minIndex = i;
									}
								}
								// 设置默认选中
								this.selectedZoneDisplay = this.zoneDisplayList[minIndex];
								this.form.domain = this.zoneList[minIndex].domain;
							}
						} else {
							this.$u.toast('获取分区失败');
						}
					})
					.catch(err => {
						console.error('分区请求失败：', err);
						this.$u.toast('网络错误，无法获取分区');
					});
			},

			// 分区变更处理
			onZoneChange(e) {
				const index = e.detail.value;
				this.selectedZoneDisplay = this.zoneDisplayList[index];
				this.form.domain = this.zoneList[index].domain;
			},
			tab: function(index) {
				this.tabIndex = index
			},
			downloadCaptcha: function() {
				// var that = this
				// that.form.captcha = ''
				// that.$u.post('/addons/fastim/api.user/captchaPre', {}).then(res => {
				// 	that.ws.captchaId = res.data.captcha_id;
				// 	that.captchaPath = this.ws.buildUrl('default') +
				// 		'/addons/fastim/api.user/captcha?captcha_id=' + res.data.captcha_id
				// }).catch(res => {
				// 	that.$u.toast('验证码请求失败，请重试！');
				// })
			},
			getCode: function() {
				var that = this
				if (!that.form.mobile) {
					that.$u.toast('请输入手机号');
					return;
				}
				if (that.$refs.uCode.canGetCode) {
					uni.showLoading({
						title: '正在获取验证码',
						mask: true
					});
					that.$u.post('/api/sms/send', {
						event: 'login',
						mobile: that.form.mobile
					}).then(res => {
						// if (res.code == 1) {
						// 	uni.hideLoading();
						// 	that.$u.toast('验证码已发送');
						// 	that.$refs.uCode.start();
						// } else {
						// 	that.modelContent = res.msg
						// 	that.modelShow = true
						// }
					}).catch(res => {
						that.$u.toast('请求失败，请重试！');
					})
				} else {
					that.$u.toast('倒计时结束后再发送');
				}
			},
			codeChange(text) {
				this.codeTips = text;
			},
			loginTUICallKit(userID) {
				userID = userID.toString();
				const userSig = genTestUserSig(userID).userSig;
				const SDKAppID = genTestUserSig('').sdkAppID;
				console.log("当前登录的id", userID);
				if (!SDKAppID) {
					console.error('请检查 uni-app/debug/GenerateTestUserSig.js 文件的 sdkAppID、usersig 是否填写');
				} else if (typeof SDKAppID !== 'number') {
					console.error('请检查 uni-app/debug/GenerateTestUserSig.js 文件下的 sdkAppID 是否为数字number 类型');
				}
				uni.$TUIKit.login({
					userID: userID,
					userSig: userSig
				});
				uni.$TUICallKit.login({
					SDKAppID,
					userID: userID,
					userSig: userSig,
				}, (res) => {
					console.log("res", res);
					if (res.code === 0) {
						// 开启悬浮窗
						uni.$TUICallKit.enableFloatWindow(true);
					} else {
						console.error('login failed, failed message = ', res.msg);
					}

				});
				getApp().globalData.userID = userID;
				getApp().globalData.userSig = userSig;
			},
			submit: function() {
				var that = this
				// that.$refs.uForm.validate(valid => {
				// if (valid) {
				that.loginFormButtonDisabled = true
				that.form.tab = that.tabIndex
				that.form.captcha_id = that.ws.captchaId
				that.form.account = (that.tabIndex == 0) ? that.form.username : that.form.mobile;
				that.$u.post('/addons/fastim/api.user/login', that.form).then(res => {
					that.loginFormButtonDisabled = false
					if (res.code == 1) {
						uni.setStorageSync('userinfo', res.data.userinfo);
						// 登录成功后存储用户选择的分区域名
						uni.setStorageSync('selectedZoneDomain', that.form.domain); // 存储域名到本地

						// 更新服务分区
						// const userId = res.data.userinfo.id;
						// console.log(userId);
						// that.updateServiceDomain(userId, selectedDomain);
						that.ws.init(res.data.userinfo.token, res.data.userinfo.auth_token)
						//登录腾讯音视频
						console.log('userinfo', res.data.userinfo);
						// #ifndef H5
						that.loginTUICallKit(res.data.userinfo.id);
						// #endif
						uni.reLaunch({
							url: '/pages/message/message'
						})
					} else {
						// console.log(res.msg)
						uni.showToast({
							'title': res.msg
						})
						that.downloadCaptcha()
						that.modelContent = res.msg
						that.modelShow = true
					}
				}).catch(res => {
					that.downloadCaptcha()
					that.loginFormButtonDisabled = false
					that.$u.toast('请求失败，请重试！');
				})
				// }
				// });
			},


			goRegister: function() {
				uni.navigateTo({
					url: '/pages/center/register'
				})
			}
		}
	}
</script>
<style lang="less" scoped>
	.page {
		// background: #fff;
		width: 100%;
		height: 100vh;
		padding: 100rpx;
		margin-top: 60px;
		// transform: translateY(30px);
		// position: relative;
		// top: 30px;
		box-sizing: border-box;

		.welcome {
			margin-bottom: 150rpx;

			.w {
				font-size: 38rpx;
			}

			.big {
				font-size: 54rpx;
				font-weight: 700;
			}
		}

		.login-wrap {
			.login-type {
				font-size: 34rpx;
				display: flex;
				align-items: center;
			}

			.getCode {
				margin-left: 20rpx;
				border: 1rpx solid #000000;
				border-radius: 10rpx;
				height: 60rpx;
				width: 178rpx;
				text-align: center;
				line-height: 60rpx;
				font-size: 24rpx;
				margin-bottom: 10rpx;
			}
		}

		.submit {
			margin: auto;
			margin-top: 100rpx;

			.btn {
				background: #1AAD19;
				width: 555rpx;
				height: 100rpx;
				color: #fff;
				text-align: center;
				line-height: 100rpx;
				font-size: 35rpx;
				border-radius: 10rpx;
			}
		}

		.reading {
			position: fixed;
			bottom: 100rpx;
			left: 0;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #a0a0a0;
			font-size: 24rpx;
		}
	}
</style>
<style lang="scss">
	page {
		background-color: $--bg-color;
	}

	.login-bg {
		width: 100vw;
	}

	.login-menu-box {
		position: relative;
	}

	.login-menu {
		display: flex;
		width: 80vw;
		margin: 0 auto;
		align-items: center;
		background-color: $--white;
		border-radius: 50rpx;
		position: absolute;
		top: -40rpx;
		left: 10vw;
		box-shadow: 0 0 10px rgba(0, 0, 0, .2);
	}

	.login-button {
		height: 80rpx;
		width: 50%;
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
		line-height: 80rpx;
		color: $--gray;
		border-radius: 50rpx;
		background: $--white;
	}



	.login-form {
		display: block;
		width: 78vw;
		padding-top: 140rpx;
		margin: 0 auto;
	}

	.login-footer-box {
		position: fixed;
		bottom: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100vw;
	}

	.login-footer-box-left {
		text-decoration: underline;
		font-size: 28rpx;
		color: $--blue;
	}

	.captcha-img {
		width: 200rpx;
		max-height: 100rpx;
	}

	.picker-view {
		display: flex;
		align-items: center;
		color: #333;
	}

	/* 在线人数的绿色字体 */
	.online-count {
		color: #28a745;
		font-weight: bold;
	}
</style>